package com.nxy.cpfsfe.busi.bbatproc;

import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nxy.cpfsfe.PubBeanSerial;
import com.nxy.cpfsfe.busi.bbatproc.chka.NCSChkASrv;
import com.nxy.cpfsfe.busi.btmgtsk.BTmgEndDChkATaskBean;
import com.nxy.cpfsfe.enumtype.*;
import com.nxy.cpfsfe.mybatis.mapper.*;
import com.nxy.cpfsfe.mybatis.pojo.*;
import com.nxy.cpfsfe.util.*;
import com.nxy.cpfsfe.util.JredisUtil.TimeoutableJedisPubSub;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

public class BBatProcWebSrvBean {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(BBatProcWebSrvBean.class);
	
	/**
	 * 
	 * Description:统一接收内管系统发送来的请求，根据initrSeqno中带的方法名
	 * 			     调用对应方法进行处理
	 *
	 * @author jjw
	 * @data 2019年9月18日
	 */
	public void unifySrv(){
		
		try{
			String tpId = DtaInfo.getInstance().getTpId();
			String initrSeqno = (String) EPOper.get(tpId, "ReqBean[0].head[0].initrSeqno");
			String bizMsg = (String)EPOper.get(tpId, "ReqBean[0].body[0].BizMsg");
			MDC.put("ROUTINGKEY" , LogUtil.getLogFileName("MGR", StringUtils.isNotBlank(initrSeqno) ? initrSeqno : "unknown"));
			if(initrSeqno == null){
				throw new BaseException(RespCd.NCPO0110,"报文体缺少initrSeqno属性");
			}
			if(bizMsg == null){
				throw new BaseException(RespCd.NCPO0110,"报文体缺少BizMsg属性");
			}
			LOGGER.info("内管调用批量类Web统一处理模块[{}]，请求体：[{}]",initrSeqno,bizMsg);
			
			Method method = this.getClass().getDeclaredMethod(initrSeqno,String.class);
			method.setAccessible(true);
			method.invoke(this,bizMsg);
			
			LOGGER.info("内管调用批量类Web统一处理模块[{}]成功",initrSeqno);
		}catch(BaseException e){
			//业务异常处理
			String tpId = DtaInfo.getInstance().getTpId();
            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", e.getErrorCode());
            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", e.getErrorDesc());
            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
            respBody.setValue("BizMsg", "F");
            
            //异常日志记录
            String errorMsg = String.format("内管调用批量类Web统一处理模块失败，错误码:%s,错误信息:%s",e.getErrorCode(),e.getErrorDesc());
            LOGGER.error(errorMsg,e);
		}catch(InvocationTargetException e){
			Throwable tarEx = e.getTargetException();
			
			if(tarEx instanceof BaseException){
				//业务异常
				String tpId = DtaInfo.getInstance().getTpId();
	            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", ((BaseException)tarEx).getErrorCode());
	            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", ((BaseException)tarEx).getErrorDesc());
	            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
	            respBody.setValue("BizMsg", "F");
	            
	            String errorMsg = String.format("内管调用批量类Web统一处理模块失败，错误码:%s,错误信息:%s",((BaseException)tarEx).getErrorCode(),((BaseException)tarEx).getErrorDesc());
	            LOGGER.error(errorMsg,tarEx);
			}else{
				//未知异常
				String tpId = DtaInfo.getInstance().getTpId();
	            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", "90000");
	            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "未知异常");
	            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
	            respBody.setValue("BizMsg", "F");
	            
	            LOGGER.error("内管调用批量类Web统一处理模块失败，发生未知异常",tarEx);
			}
		}catch(Throwable e){
			//未知异常日志记录
            String tpId = DtaInfo.getInstance().getTpId();
            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", "90000");
            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "未知异常");
            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
            respBody.setValue("BizMsg", "F");
            
            LOGGER.error("内管调用批量类Web统一处理模块失败，发生未知异常",e);
		}finally {
			try{
				MDC.clear();
				//资源对象释放
			}catch (Exception e){
				//异常日志记录
				String errorMsg = "释放MDC资源异常";
				LOGGER.error(errorMsg,e);
			}
		}
		
	}
	
	/**
	 * 
	 * Description:成员行与通道对账
	 *
	 * @author jjw
	 * @data 2019年9月21日
	 */
	private void doChlChkA(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		
		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		String orgId = reqBody.getString("orgId");
		String chkAD = reqBody.getString("chkAD");
		String mfeTyp = reqBody.getString("mfeTyp");
		
		//查询机构开通的通道
		TrChlBizTypMapper trChlBizTypMapper = sqlSession.getMapper(TrChlBizTypMapper.class);
		List<TrSysBizTyp> trSysBizTyps = new ArrayList<TrSysBizTyp>();
		TrSysBizTyp trSysBizTyp = new TrSysBizTyp();
		trSysBizTyp.setOrgId(orgId);
		trSysBizTyps.add(trSysBizTyp);
		List<String> pCIds = trChlBizTypMapper.queryOpenChlByOrgId(trSysBizTyps);
		
		if(pCIds == null || pCIds.size() == 0){
			String errMsg = String.format("机构[%s]未开通任何通道，不能进行[%s]日对账", orgId,chkAD);
			throw new BaseException(RespCd.NCPO6068,errMsg);
		}

		try{
			for(String pCId : pCIds){
				if("NCS".equals(pCId)){
					new NCSChkASrv(orgId,pCId,DateUtil.str2Date(chkAD,"yyyyMMdd"),mfeTyp).chkAProcess();
				}else{
					String errMsg = String.format("当前系统不支持[%s]通道的对账",pCId);
					throw new BaseException(RespCd.NCPS2001,errMsg);
				}
			}
		}catch (BaseException e){
			if(e.getErrorCode().equals(RespCd.NCPO0001)){
				LOGGER.warn(e.getErrorDesc());
				String tpId = DtaInfo.getInstance().getTpId();
				EPOper.put(tpId, "RspBean[0].head[0].rspsCd", e.getErrorCode());
				EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", e.getErrorDesc());
				CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
				respBody.setValue("BizMsg", "F");
				return;
			}else{
				throw e;
			}
		}


		//触发生成业务系统对账文件流程
		BTmgEndDChkATaskBean.timeTask(DateUtil.str2Date(chkAD,"yyyyMMdd"),"BBat");
		
		String tpId = DtaInfo.getInstance().getTpId();
		EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
		EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
		CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
		respBody.setValue("BizMsg", "S");
		
	}
	
	/**
	 * 
	 * Description:查询成员行资金汇总
	 *
	 * @author jjw
	 * @data 2019年9月18日
	 */
	private void mbrBkSum(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		JSONObject respJson = new JSONObject();
		
		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		String orgNm = reqBody.getString("orgNm");
		String chkAD = reqBody.getString("chkAD");
		String bNo = reqBody.getString("bNo");
		Integer start = Integer.parseInt(reqBody.getString("NEXT_KEY"));
		Integer count = Integer.parseInt(reqBody.getString("PAGE_SIZE"));

		TdChkaSumMapper tdChkaSumMapper = sqlSession.getMapper(TdChkaSumMapper.class);
		int total = tdChkaSumMapper.queryCountSumAmtByBNo(bNo, chkAD, orgNm);
		List<Map<String,Object>> sumResults = tdChkaSumMapper.querySumAmtByBNo(bNo, chkAD,orgNm,start,count);
		
		respJson.put("TOTAL_NUM", total);
		respJson.put("data", sumResults);
		
		String tpId = DtaInfo.getInstance().getTpId();
        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
        CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
        respBody.setValue("BizMsg", respJson.toJSONString());
		
	}
	
	/**
	 * 
	 * Description:查询业务系统资金汇总
	 *
	 * @author jjw
	 * @data 2019年9月19日
	 */
	private void bizSysSum(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		JSONObject respJson = new JSONObject();
		
		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		String bizSysId = reqBody.getString("bizSysId");
		String bNo = reqBody.getString("bNo");
		String chkAD = reqBody.getString("chkAD");
		Integer start = Integer.parseInt(reqBody.getString("NEXT_KEY"));
		Integer count = Integer.parseInt(reqBody.getString("PAGE_SIZE"));
		
		TbBizChkaSumMapper tbBizChkaSumMapper = sqlSession.getMapper(TbBizChkaSumMapper.class);
		int total = tbBizChkaSumMapper.queryCountSumAmtByBizSysId(bizSysId,bNo, chkAD);
		List<Map<String,Object>> sumResults = tbBizChkaSumMapper.querySumAmtByBizSysId(bizSysId, bNo,chkAD,start,count);
		
		respJson.put("TOTAL_NUM", total);
		respJson.put("data", sumResults);
		
		String tpId = DtaInfo.getInstance().getTpId();
        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
        CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
        respBody.setValue("BizMsg", respJson.toJSONString());
		
	}
	
	/**
	 * 
	 * Description:查询成员行对账进度
	 *
	 * @author jjw
	 * @data 2019年9月19日
	 */
	private void mbrBkChkASchedule(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		JSONObject respJson = new JSONObject();
		
		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		String orgId = reqBody.getString("orgId");
		String chkASta = reqBody.getString("chkASta");
		String orgNm = reqBody.getString("orgNm");
		String chkAD = reqBody.getString("chkAD");
		Integer start = reqBody.getString("NEXT_KEY") != null ? Integer.parseInt(reqBody.getString("NEXT_KEY")) : null;
		Integer count = reqBody.getString("PAGE_SIZE") != null ? Integer.parseInt(reqBody.getString("PAGE_SIZE")) : null;
		
		TePChlSettMapper tePChlSettMapper = sqlSession.getMapper(TePChlSettMapper.class);
		int total = tePChlSettMapper.queryCountChkASchedule(orgId, chkASta, orgNm, chkAD);
		List<Map<String,Object>> queryResults = tePChlSettMapper.queryChkASchedule(orgId, chkASta, orgNm, chkAD, start, count);
		
		respJson.put("TOTAL_NUM", total);
		respJson.put("data", queryResults);
		
		String tpId = DtaInfo.getInstance().getTpId();
        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
        CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
        respBody.setValue("BizMsg", respJson.toJSONString());
		
	}
	
	/**
	 * 
	 * Description:导出差错信息
	 *
	 * @author jjw
	 * @data 2019年9月21日
	 */
	private void exportErr(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		JSONObject respJson = new JSONObject();
		
		JSONArray reqBody = null;
		try{
			reqBody = JSON.parseArray(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		Iterator<Object> iterator = reqBody.iterator();
		List<Integer> idsList = new ArrayList<Integer>();
		while(iterator.hasNext()){
			JSONObject idJSONObject = (JSONObject)iterator.next();
			if(!"on".equals(idJSONObject.getString("id"))){
				idsList.add(Integer.parseInt(idJSONObject.getString("id")));
			}
		}
		
		TeXErrMapper teXErrMapper = sqlSession.getMapper(TeXErrMapper.class);
		List<Map<String,Object>> teXErrs = teXErrMapper.queryErrByIds(idsList);
		
		respJson.put("data", teXErrs);
		
		String tpId = DtaInfo.getInstance().getTpId();
        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
        CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
        respBody.setValue("BizMsg", respJson.toJSONString());
		
	}

	/**
	 *
	 * Description:业务系统汇总与NCS汇总差异查询
	 *
	 * @author jjw
	 * @data 2019年10月17日
	 */
	private void sumDifference(String bizMsg){

		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		JSONObject respJson = new JSONObject();

		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}

		String chkAD = reqBody.getString("chkAD");
		Integer start = Integer.parseInt(reqBody.getString("NEXT_KEY"));
		Integer count = Integer.parseInt(reqBody.getString("PAGE_SIZE"));

		TbBizChkaSumMapper tbBizChkaSumMapper = sqlSession.getMapper(TbBizChkaSumMapper.class);
		TdChkaSumMapper tdChkaSumMapper = sqlSession.getMapper(TdChkaSumMapper.class);

		int total = tbBizChkaSumMapper.queryCountSumAmtByChkAD(chkAD);
		if(total == 0){
			respJson.put("TOTAL_NUM", total);
			respJson.put("data", new ArrayList<>());

			String tpId = DtaInfo.getInstance().getTpId();
			EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
			EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
			CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
			respBody.setValue("BizMsg", respJson.toJSONString());
			return;
		}

		List<Map<String,Object>> respList = tbBizChkaSumMapper.querySumAmtByChkAD(chkAD,start,count);
		for(Map<String,Object> resp : respList){
			TdChkaSum tdChkaSum = tdChkaSumMapper.querySumAmtByChkAD((String)resp.get("chkAD"));
			resp.put("bizTotalAmt",((BigDecimal)resp.get("bizLoanTotAmt")).subtract((BigDecimal)resp.get("bizDrTotAmt")).setScale(2));
			resp.put("ncsTotalAmt",tdChkaSum.getLoanTotAmt().subtract(tdChkaSum.getDrTotAmt()).setScale(2));
			resp.put("diffTotalAmt",((BigDecimal)resp.get("bizTotalAmt")).subtract((BigDecimal) resp.get("ncsTotalAmt")).setScale(2));
			resp.put("ncsDrTotDN",tdChkaSum.getDrTotDN());
			resp.put("ncsDrTotAmt",tdChkaSum.getDrTotAmt());
			resp.put("ncsLoanTotDN",tdChkaSum.getLoanTotDN());
			resp.put("ncsLoanTotAmt",tdChkaSum.getLoanTotAmt());
			resp.put("diffDrTotDN",((BigDecimal)resp.get("bizDrTotDN")).subtract(new BigDecimal(tdChkaSum.getDrTotDN())));
			resp.put("diffDrTotAmt",((BigDecimal)resp.get("bizDrTotAmt")).subtract(tdChkaSum.getDrTotAmt()).setScale(2));
			resp.put("diffLoanTotDN",((BigDecimal)resp.get("bizLoanTotDN")).subtract(new BigDecimal(tdChkaSum.getLoanTotDN())));
			resp.put("diffLoanTotAmt",((BigDecimal)resp.get("bizLoanTotAmt")).subtract(tdChkaSum.getLoanTotAmt()).setScale(2));
		}

		respJson.put("TOTAL_NUM", total);
		respJson.put("data", respList);

		String tpId = DtaInfo.getInstance().getTpId();
		EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
		EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
		CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
		respBody.setValue("BizMsg", respJson.toJSONString());

	}
	
	/**
	 * 内管发起303自由格式报文
	 */
	
	private void bBatFreeFmtSrv(String bizMsg) {
		SqlSession sqlSession = null;
		ToSysNtcMapper toSysNtc = null;
		String tpId = DtaInfo.getInstance().getTpId();	
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口		
		//String sndAppCd = (String) EPOper.get(tpId, "ReqBean[0].head[0].sndAppCd");
		LOGGER.debug("接收到输入BizMsg报文数据:[{}]" , bizMsg);
		JSONObject jsonObject = JSONObject.parseObject(bizMsg);		
		Map<String, String> bizmap = new HashMap<String, String>();
		bizmap.put("sndOrgNo", jsonObject.getString("sndOrg"));
		bizmap.put("recpOrgNo", jsonObject.getString("recpOrg"));
		bizmap.put("ntcCont", jsonObject.getString("msgContent"));
		bizmap.put("msgId", PubBeanSerial.getInstance().getSeqNoAndIncrea("MSGID"));
		bizmap.put("seqNb", PubBeanSerial.getInstance().getSeqNoAndIncrea("seqNb"));
		bizmap.put("ntcTyp", MsgCdOrTpEnum.MSGCD_303.getCode());//自由格式类型
		bizmap.put("bizSta", StatEnum.BIZSTA_ING.getCode());
		bizmap.put("ntcTm", DateUtil.getTimestamp(new Date()));
		//登记自由格式信息
		try {
			sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
			toSysNtc = sqlSession.getMapper(ToSysNtcMapper.class);
			toSysNtc.insert(bizmap);
		} catch (Throwable e) {
			LOGGER.error("303自由格式信息入库异常,msgId=["+bizmap.get("msgId")+"]",e);
			throw new BaseException(RespCd.NCPS5002, e, "自由格式服务错误");
		}
	
		String rspCd = returnGWNPS303(bizmap);
		String msg = "";
		CompSDO outputSdo = EPOper.getCompSDO(tpId, "RspBody"); // 获取输出接口
		if(RespCd.NCPI0000.equals(rspCd)){
			//订阅者阻塞等待
			TimeoutableJedisPubSub totjpb = JredisUtil.getInstance().redisSubscribe(bizmap,30000);
			if(totjpb.flag){	
				if(MsgCdOrTpEnum.MSGCD_900.getCode().equals(XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/header/msg/msgCd"))){
					String resStat = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/PrcSts");
					String rjctInf = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/RjctInf");
					if(StatEnum.STAR_PR02.getCode().equals(resStat)){				
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "交易成功！");
						msg = "交易成功！";
						LOGGER.debug("交易成功:[{}]" , bizmap.get("msgId"));
					}
					else {
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", rjctInf);	
						msg = rjctInf;
						LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("msgId"),rjctInf);
					}
				}else {//911回来的处理
					String rjctInf = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/DscrdMsgNtfctn/DscrdInf/RjctInf");
					EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
					EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", rjctInf);	
					msg = rjctInf;
					LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("msgId"),rjctInf);
				}
		    	
			}else{			
		        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6076);
		        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "服务响应超时,请查证！");
		        msg = "服务响应超时,请查证！";
		        bizmap.put("bizSta", StatEnum.BIZSTA_ING.getCode());
				try {
					toSysNtc = sqlSession.getMapper(ToSysNtcMapper.class);
					toSysNtc.update(bizmap);
					LOGGER.debug("服务响应超时,请查证:[{}]" , bizmap.get("msgId"));
				} catch (Throwable e) {
					LOGGER.error("303自由格式ToSysNtc表更新异常,msgId=["+bizmap.get("msgId")+"]",e);
				}
			}				
		}else {		
			EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6047);
			EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "调用网关服务失败！");		
			msg = "调用网关服务失败！";
			bizmap.put("bizSta",StatEnum.BIZSTA_FAIL.getCode());
			try {
				toSysNtc = sqlSession.getMapper(ToSysNtcMapper.class);
				toSysNtc.update(bizmap);
				LOGGER.debug("调用网关服务失败:[{}]" , jsonObject.getString("sndOrgNo"));
			} catch (Throwable e) {
				LOGGER.error("303自由格式ToSysNtc表更新异常,msgId=["+bizmap.get("msgId")+"]",e);
			}
		}

		JSONObject respJson = new JSONObject();
		List list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("deal",msg);
        map1.put("msgId",bizmap.get("msgId"));
        list.add(map1);
        respJson.put("data", list);
		outputSdo.setValue("BizMsg", respJson.toJSONString());
		LOGGER.info("303自由格式返回内管[{}]",respJson.toJSONString());
	}
	
	
	public String returnGWNPS303(Map<String, String> bizmap){
		String tpId = DtaInfo.getInstance().getTpId();	
		String rspCd = "";
		try {
			String bizMsg303 = ResponseUtil.build303Xml(bizmap);		
			//转发给网关
		    LOGGER.debug("rpc调用网关发送NPS303开始......");
			//判断如果是老系统，sndAppCd为该成员行所属的系统编号
			ToParm toParm = queryBnoCls(bizmap.get("sndOrgNo"));
			if(toParm!=null){
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", toParm.getDataCd());
			}else {
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", SysEcodeEnum.CPFS.getCode());
			}
		    EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.NCS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.MSGCD_303.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].initrSeqno",bizmap.get("seqNb"));
		    EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", bizMsg303);   
		    rspCd = RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	
		} catch (Throwable e) {
			rspCd = RespCd.NCPO6047;
			LOGGER.error("303自由格式更新异常,msgId=["+bizmap.get("msgId")+"]",e);
		}
		return rspCd;
	}
	
	//内管登录退出请求
	private void bBatLgnReqSrv(String bizMsg) {
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		Map<String, Object> map = null;
		String tpId = DtaInfo.getInstance().getTpId();	
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口		
//		bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
		//String sndAppCd = (String) EPOper.get(tpId, "ReqBean[0].head[0].sndAppCd");
		LOGGER.debug("接收到输入BizMsg报文数据:[{}]" , bizMsg);
		JSONObject jsonObject = JSONObject.parseObject(bizMsg);
		String sndMbrCd = jsonObject.getString("orgBNo");
		String loginOprTp = jsonObject.getString("ncsSta");
		LOGGER.debug("发送成员行行号:[{}]" , sndMbrCd);
		LOGGER.debug("系统请求操作类型:[{}]" , loginOprTp);	
		String seqNb = PubBeanSerial.getInstance().getSeqNoAndIncrea("seqNb");
		Map<String, String> bizmap = new HashMap<String, String>();
		bizmap.put("sndOrgNo", sndMbrCd);
		bizmap.put("loginOprTp", loginOprTp);
		bizmap.put("seqNb", seqNb);
		bizmap.put("msgId", PubBeanSerial.getInstance().getSeqNoAndIncrea("MSGID"));
		String rspCd = returnGWNPS805(bizmap);		
		//初始化处理
		ToOrg toOrg = new ToOrg();
		toOrg.setOrgBNo(sndMbrCd);
		ToOrgMapper toOrgMap = sqlSession.getMapper(ToOrgMapper.class);
		ToOrg toOrgOb = toOrgMap.queryByBNo(toOrg);
		String ncsSta = toOrgOb.getNcsSta();
		if(ncsSta == null || "".equals(ncsSta)){
			toOrg.setNcsSta("OT09");     //处理中
			toOrg.setUpdTm(new Date());
			toOrgMap.update(toOrg);
		}
		//刷新时间戳
		TpRefrshTblnm tblnm = new TpRefrshTblnm();
		tblnm.setTblNm("to_org");
		tblnm.setUpdtTime(DateUtil.getDateTime());
		sqlSession.getMapper(TpRefrshTblnmMapper.class).update(tblnm);
		String msg = "";		
		if(RespCd.NCPI0000.equals(rspCd)){
			//订阅者阻塞等待
			TimeoutableJedisPubSub totjpb = JredisUtil.getInstance().redisSubscribe(bizmap,30000);				
			if(totjpb.flag){
				if(MsgCdOrTpEnum.MSGCD_806.getCode().equals(XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/header/msg/msgCd"))){
					String prcSts =XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/LoginRspn/LoginRspnInf/PrcSts");
					String pjctInf =XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/LoginRspn/LoginRspnInf/RjctInf");
					if(StatEnum.STAR_PR02.getCode().equals(prcSts)){
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "交易成功！");
						msg = "交易成功！";
						LOGGER.debug("交易成功:[{}]" , bizmap.get("msgId"));
					}else{
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", pjctInf);	
						msg = pjctInf;
						LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("msgId"),pjctInf);
					}
				}else if(MsgCdOrTpEnum.MSGCD_900.getCode().equals(XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/header/msg/msgCd"))){
					//String resStat = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/PrcSts");
					String rjctInf = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/RjctInf");			
					EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
					EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", rjctInf);	
					msg = rjctInf;
					LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("msgId"),rjctInf);
				}else{  //911
					String rjctInf = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/DscrdMsgNtfctn/DscrdInf/RjctInf");
					EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
					EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", rjctInf);	
					msg = rjctInf;
					LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("msgId"),rjctInf);
				}
			}else{			
		        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6076);
		        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "服务响应超时,请查证！");
		        msg = "服务响应超时,请查证！";	        
			}
		}else{
			EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6047);
			EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "调用网关服务失败！");		
			msg = "调用网关服务失败！";
		}
		
		//向内管返回信息
		JSONObject respJson = new JSONObject();
		CompSDO outputSdo = EPOper.getCompSDO(tpId, "RspBody"); // 获取输出接口
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();      
        map1.put("deal",msg);
        list.add(map1);
        respJson.put("data", list);
		outputSdo.setValue("BizMsg", respJson.toJSONString());				
	}
	
	public String returnGWNPS805(Map<String, String> bizmap){
		String rspCd = "";
		String tpId = DtaInfo.getInstance().getTpId();	
		String seqNo = PubBeanSerial.getInstance().getSeqNoAndIncrea(SysEcodeEnum.CPFS.getCode());
		try {
			String bizMsg805 = ResponseUtil.build805Xml(bizmap);
			//转发给网关
		    LOGGER.debug("rpc调用网关发送NPS805开始......");
			//判断如果是老系统，sndAppCd为该成员行所属的系统编号
			ToParm toParm = queryBnoCls(bizmap.get("sndOrgNo"));
			if(toParm!=null){
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", toParm.getDataCd());
			}else {
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", SysEcodeEnum.CPFS.getCode());
			}
		    EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.NCS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.MSGCD_805.getCode());	    	
	    	EPOper.put(tpId, "ReqBean[0].head[0].initrSeqno",seqNo);
		    EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", bizMsg805);   
		    rspCd = RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	
		}catch(Exception e){
			rspCd = RespCd.NCPO6047;
			LOGGER.error("NPS805调用网关异常,initrSeqno=["+seqNo+"]",e);
			throw new BaseException(RespCd.NCPO6047,e,"调用网关服务异常");
		}
		return rspCd;
	}
	
	//数字证书绑定
	private void bBatDgtlCrdlSrv(String bizMsg) {
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		Map<String, Object> map = null;
		String tpId = DtaInfo.getInstance().getTpId();	
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口		
		//bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
		//String sndAppCd = (String) EPOper.get(tpId, "ReqBean[0].head[0].sndAppCd");
		LOGGER.debug("接收到输入BizMsg报文数据:[{}]" , bizMsg);
		JSONObject jsonObject = JSONObject.parseObject(bizMsg);
		//TODO 处理数字证书绑定
		String bankNo = jsonObject.getString("bankNo");
		String bndFlg = jsonObject.getString("bndFlg");
		String crdlDN = jsonObject.getString("crdlDN");
		LOGGER.debug("发送成员行行号:[{}]" , bankNo);
		LOGGER.debug("绑定标识:[{}]" , bndFlg);
		LOGGER.debug("DN值:[{}]" , crdlDN);
		/*//获取DN值
		ToNcsCrdl toNcsCrdl = new ToNcsCrdl();
		toNcsCrdl.setBankNo(bankNo);
		ToNcsCrdlMapper toNcsCrdlMap = sqlSession.getMapper(ToNcsCrdlMapper.class);
		ToNcsCrdl toNcsCrdlOb = toNcsCrdlMap.queryByBNo(toNcsCrdl);*/
		String msg = "";

		String seqNb = PubBeanSerial.getInstance().getSeqNoAndIncrea("seqNb");
		Map<String, String> bizmap = new HashMap<String, String>();
		bizmap.put("sndOrgNo", bankNo);
		bizmap.put("bndFlg", bndFlg);
		bizmap.put("seqNb", seqNb);	
		bizmap.put("crdlDN", crdlDN);	
		String rspCd = returnGWNPS903(bizmap);	
		if(RespCd.NCPI0000.equals(rspCd)){
			//订阅者阻塞等待
			TimeoutableJedisPubSub totjpb = JredisUtil.getInstance().redisSubscribe(bizmap,30000);				
			if(totjpb.flag){
				if(MsgCdOrTpEnum.MSGCD_900.getCode().equals(XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/header/msg/msgCd"))){
					String resStat = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/PrcSts");
					String rjctInf = XmlUtil.getValByXPath(totjpb.resMsg,"/transaction/body/CmonConf/CmonConfInf/RjctInf");
					if(StatEnum.STAR_PR02.getCode().equals(resStat)||StatEnum.STAR_PR00.getCode().equals(resStat)){				
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "交易成功！");
						msg = "交易成功！";
						LOGGER.debug("交易成功:[{}]" , bizmap.get("seqNb"));
					}
					else {
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd",  RespCd.NCPO6047);
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", rjctInf);	
						msg = rjctInf;
						LOGGER.debug("msgId=[{}]rjctInf:[{}]" , bizmap.get("seqNb"),rjctInf);
					}
			   }
			}else{			
		        EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6076);
		        EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "服务响应超时,请查证！");
		        msg = "服务响应超时,请查证！";	        
			}
		}else if(RespCd.NCPO4999.equals(rspCd)){
			EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO4999);
			EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "签名者证书无效,证书DN值不可用！");
			msg = "签名者证书无效,无法找到签名用的私钥！";
		}else{
			EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPO6047);
			EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "调用网关服务失败！");		
			msg = "调用网关服务失败！";
		}	

		 		
		JSONObject respJson = new JSONObject();
		CompSDO outputSdo = EPOper.getCompSDO(tpId, "RspBody"); // 获取输出接口
		List list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("deal",msg);
        list.add(map1);
        respJson.put("data", list);
		outputSdo.setValue("BizMsg", respJson.toJSONString());		
	}
	
	public String returnGWNPS903(Map<String, String> bizmap){
		String rspCd = "";
		String tpId = DtaInfo.getInstance().getTpId();		
		String bizMsg903 = ResponseUtil.build903Xml(bizmap);
		LOGGER.debug("NPS903报文[{}]",bizMsg903);		
		//转发给网关
	    LOGGER.debug("rpc调用网关发送NPS903开始......");
	    try{
			//判断如果是老系统，sndAppCd为该成员行所属的系统编号
			ToParm toParm = queryBnoCls(bizmap.get("sndOrgNo"));
			if(toParm!=null){
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", toParm.getDataCd());
			}else {
				EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", SysEcodeEnum.CPFS.getCode());
			}
		    EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.NCS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.MSGCD_903.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].crdlDN", bizmap.get("crdlDN"));
	    	String seqNo = PubBeanSerial.getInstance().getSeqNoAndIncrea(SysEcodeEnum.CPFS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].initrSeqno",seqNo);
		    EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", bizMsg903);
			rspCd = RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	
	    }catch(Exception e){
	    	rspCd = RespCd.NCPO6047;
	    	LOGGER.error("调用网关转发NPS.903报文服务失败",e);
			throw new BaseException(RespCd.NCPO6047,e,"调用网关服务异常");
	    }
	    return rspCd;
	}

	public ToParm queryBnoCls(String bno) {
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		ToParmMapper toParmMapper = sqlSession.getMapper(ToParmMapper.class);
		ToParm toParm = new ToParm();
		toParm.setDataVal(bno);
		toParm.setDataTyp(DataTypeEnum.BIZSYS.getCode());
		List<ToParm> list = toParmMapper.query(toParm);
		if(list != null){
			if(list.size()==1){
				return list.get(0);
			}else if(list.size()==0){
				return null;
			}else{
				throw new BaseException(RespCd.NCPO0007,String.format("参数信息表数据异常，类型:[%s],行号:[%s]",DataTypeEnum.BIZSYS.getCode(),bno));
			}
		}
		return null;
	}
	
	
	

}
